import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Website, WebsiteDocument } from './schemas/website.schema';
import { PageView, PageViewDocument } from './schemas/page-view.schema';

@Injectable()
export class IpMongoService {
  constructor(
    @InjectModel(Website.name)
    private websiteModel: Model<WebsiteDocument>,
    @InjectModel(PageView.name)
    private pageViewModel: Model<PageViewDocument>,
  ) {}

  async getIpVisits(ip: string, websiteId?: string, startDate?: string, endDate?: string): Promise<any> {
    try {
      const match: any = { ip };
      
      if (websiteId) {
        match.websiteId = new Types.ObjectId(websiteId);
      }
      
      if (startDate && endDate) {
        match.createdAt = {
          $gte: new Date(startDate),
          $lte: new Date(endDate)
        };
      } else if (startDate) {
        match.createdAt = { $gte: new Date(startDate) };
      } else if (endDate) {
        match.createdAt = { $lte: new Date(endDate) };
      }

      const visits = await this.pageViewModel
        .find(match)
        .populate('websiteId', 'name domain')
        .sort({ createdAt: -1 })
        .exec();

      const stats = {
        totalVisits: visits.length,
        uniqueUrls: new Set(visits.map(v => v.url)).size,
        websites: new Set(visits.map(v => v.websiteId.toString())).size,
        firstVisit: visits.length > 0 ? visits[visits.length - 1].createdAt : null,
        lastVisit: visits.length > 0 ? visits[0].createdAt : null,
      };

      return {
        ip,
        stats,
        visits
      };
    } catch (error) {
      throw new Error(`获取IP访问详情失败: ${error.message}`);
    }
  }

  // 获取某网站所有访问过的IP及统计信息
  async getWebsiteIps(websiteId: string): Promise<any[]> {
    return this.pageViewModel.aggregate([
      {
        $match: {
          websiteId: new Types.ObjectId(websiteId),
          ip: { $ne: null, $exists: true }
        }
      },
      {
        $group: {
          _id: '$ip',
          totalVisits: { $sum: 1 },
          lastVisit: { $max: '$createdAt' },
          device: { $last: '$device' },
          browser: { $last: '$browser' },
          os: { $last: '$os' },
          country: { $last: '$country' },
          city: { $last: '$city' }
        }
      },
      {
        $project: {
          ip: '$_id',
          totalVisits: 1,
          lastVisit: 1,
          device: 1,
          browser: 1,
          os: 1,
          country: 1,
          city: 1,
          _id: 0
        }
      },
      {
        $sort: { lastVisit: -1 }
      }
    ]);
  }
}
